<template>
  <div class="BatchAddReport">
    <el-dialog
      :title="batchAdd.title"
      :visible.sync="batchAdd.open"
      width="1300px"
      append-to-body
      :close-on-click-modal="false"
      center
    >
      <el-form
        :inline="true"
        :model="batchForm"
        ref="batchForm"
        label-width="100px"
        :rules="roleRules"
      >
        <div class="tit">
          <h2>医院信息</h2>
        </div>

        <el-row>
          <el-form-item label="医院名称" prop="hospitalId" width="50%">
            <el-select
              size="small"
              v-model="batchForm.hospitalId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医院"
              @change="hospitalChange"
            >
              <el-option
                v-for="item in hospitalList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="科室名称" prop="officeId">
            <el-select
              size="small"
              v-model="batchForm.officeId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择科室"
              @change="officeChange"
            >
              <el-option
                v-for="item in pickOfficeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <!-- <a href="javascript:void(0);" @click="addOffice" style="margin-left: 230px">快速创建</a> -->
          </el-form-item>

          <el-form-item label="医生名称" prop="doctorId">
            <el-select
              size="small"
              v-model="batchForm.doctorId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医生"
            >
              <el-option
                v-for="item in pickDoctorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <!-- <a href="javascript:void(0);" @click="addDoctor" style="margin-left: 230px">快速创建</a> -->
          </el-form-item>
          <el-form-item label="医院项目" prop="hospitalItemIdList"  v-if="itemShow">
            <el-select
              v-model="batchForm.hospitalItemIdList"
              filterable
              clearable
              multiple
              size="small"
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医院项目"
              @change="hospitalItemChange"
            >
              <el-option
                v-for="item in pickHospitalItemList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="医检项目" prop="itemNames" v-if="!itemShow">
            <el-select
              v-model="batchForm.insItemIdList"
              filterable
              multiple
              placeholder="请选择医检项目"
              @change="itemListChange"
            >
              <el-option
                v-for="item in itemNameList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
           <el-form-item label="项目名称">
            <el-input value="新型冠状病毒核酸检测" :disabled="true"></el-input>
          </el-form-item>
        </el-row>
        <div class="tit" v-if="userRole === 1">
          <h2>医检机构</h2>
        </div>
        <el-row v-if="userRole === 1">
          <el-form-item label="医检名称" prop="institutionId">
            <el-select
              v-model="batchForm.institutionId"
              size="small"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医检机构"
              @focus="listInstitutions"
              @change="institutionChange"
            >
              <el-option
                v-for="item in pickInstitutionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="科室名称" prop="insOfficeId">
            <el-select
              v-model="batchForm.insOfficeId"
              size="small"
              filterable
              clearable
              reserve-keyword
              placeholder="请选择科室"
            >
              <el-option
                v-for="item in pickInsOfficeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="医检条码号"
            v-if="isMore == true"
            prop="insReportCode"
          >
            <el-input
              v-model="batchForm.insReportCode"
              size="small"
              @blur="checkInsCodeIsExist"
            >
            </el-input>
            <br /><span
              id="insCodeHides"
              :hidden="insCodeHide"
              style="color: red; font-size: xx-small;"
            >
              <i class="el-icon-warning" />医检条码号重复！</span
            >
          </el-form-item>
          <!-- <el-form-item label="送检时间" prop="reportBeginTime">
            <el-date-picker
              v-model="batchForm.reportBeginTime"
              type="datetime"
              size="small"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="不填则默认为当前时间"
            ></el-date-picker>
          </el-form-item> -->
          <el-form-item label="一级收样员" prop="syUserId">
            <el-select
              v-model="batchForm.syUserId"
              size="small"
              filterable
              clearable
              reserve-keyword
              placeholder="请选择一级收样员"
            >
              <el-option
                v-for="item in pickSyUserList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item id="groupSyUser" label="二级收样员" prop="syUserIdTwo">
            <el-select
              style="width: 85%;"
              v-model="batchForm.syUserIdTwo"
              size="small"
              filterable
              clearable
              reserve-keyword
              placeholder="请选择二级收样员"
            >
              <el-option
                v-for="item in pickSyUserList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-button
              style="padding:7px;"
              @click="addSubclass()"
              icon="el-icon-plus"
              plain
              round
              type="success"
              size="mini"
            ></el-button>
          </el-form-item>
          <el-form-item
            prop="syUserIdList"
            id="groupSyUser"
            v-for="(item, index) in batchForm.syUserIdList"
            size="small"
            :label="changSyUserLabel(index + 3)"
            :key="'syUserIdList' + index"
          >
            <el-select
              style="width: 85%;"
              v-model.lazy="item.userId"
              filterable
              clearable
              reserve-keyword
              placeholder="请选择收样员"
            >
              <el-option
                v-for="item in pickSyUserList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-button
              style="padding:7px;"
              @click="deleteSubclass(index)"
              icon="el-icon-close"
              plain
              round
              type="danger"
              size="mini"
            ></el-button>
          </el-form-item>
        </el-row>
        <div class="tit" style="display: flex;align-items: center;">
          <h2>用户信息</h2>
          <el-upload
            class="upload-demo"
            :action="importUrl"
            :on-change="handleChange"
            :show-file-list="false"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            :auto-upload="false"
          >
            <el-button
              style="padding:7px;margin: 5px 20px 0"
              plain
              type="primary"
              >导入表格</el-button
            >
          </el-upload>

          <span slot="tip" style="color:red" class="el-upload__tip">
            只 能 上 传 xlsx / xls 表 格 文 件
          </span>

          <el-button
            style="padding:7px;margin: 5px 20px 0"
            plain
            @click="handleDownloadImportTemplate()"
            type="warning"
            >下载导入模板</el-button
          >
        </div>

        <div>
          <el-table :data="dataList" stripe>
            <el-table-column prop="index" label="序号" width="50px"  align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.index }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="myReportCode" label="平台条码号"  align="center">
              <template slot-scope="scope">
                <input
                  style="width:85px;"
                  class="tableInput"
                  type="text"
                  v-model="scope.row.myReportCode"
                  v-show="scope.row.iseditor"
                />
                <span v-show="!scope.row.iseditor">{{
                  scope.row.myReportCode
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="insReportCode" label="医检条码号"  align="center">
              <template slot-scope="scope">
                <input
                  style="width:85px;"
                  class="tableInput"
                  type="text"
                  v-model="scope.row.insReportCode"
                  v-show="scope.row.iseditor"
                />
                <span v-show="!scope.row.iseditor">{{
                  scope.row.insReportCode
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="patientCard" label="身份证" width="180px"  align="center">
              <template slot-scope="scope">
                <input
                  style="width:145px;"
                  class="tableInput"
                  type="text"
                  v-model="scope.row.patientCard"
                  v-show="scope.row.iseditor"
                />
                <span v-show="!scope.row.iseditor">{{
                  scope.row.patientCard
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="patientPhone" label="电话" width="140px"  align="center">
              <template slot-scope="scope">
                <input
                  style="width:95px;"
                  class="tableInput"
                  type="text"
                  v-model="scope.row.patientPhone"
                  v-show="scope.row.iseditor"
                />
                <span v-show="!scope.row.iseditor">{{
                  scope.row.patientPhone
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="patientName" label="姓名" width="90px" align="center">
              <template slot-scope="scope">
                <input
                  style="width:50px"
                  class="tableInput"
                  type="text"
                  v-model="scope.row.patientName"
                  v-show="scope.row.iseditor"
                />
                <span v-show="!scope.row.iseditor">{{
                  scope.row.patientName
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="sex" label="性别" width="70px"  align="center">
              <template slot-scope="scope">
                <input
                  style="width:30px"
                  class="tableInput"
                  type="text"
                  v-model="scope.row.sex"
                  v-show="scope.row.iseditor"
                />
                <span v-show="!scope.row.iseditor">{{ scope.row.sex }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="patientAge" label="年龄" width="70px"  align="center">
              <template slot-scope="scope">
                <input
                  style="width:30px;"
                  class="tableInput"
                  type="text"
                  v-model="scope.row.patientAge"
                  v-show="scope.row.iseditor"
                />
                <span v-show="!scope.row.iseditor">{{
                  scope.row.patientAge
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="送检时间" width="100px"  align="center">
                <template slot-scope="scope">
                    <input
                      class="tableInput"
                      type="text"
                      v-model="scope.row.reportBeginTime"
                      v-show="scope.row.iseditor"
                    />
                    <span v-show="!scope.row.iseditor">{{
                      scope.row.reportBeginTime
                    }}</span>
                    <!-- <el-date-picker
                      v-model="scope.row.reportBeginTime"
                      type="datetime"
                      size="mini"
                      value-format="yyyy-MM-dd HH-mm-ss"
                      placeholder="不填则默认为当前时间">

                    </el-date-picker> -->
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"  align="center">
              <template slot-scope="scope">
                <input
                  style="width:105px;"
                  class="tableInput"
                  type="text"
                  v-model="scope.row.remark"
                  v-show="scope.row.iseditor"
                />
                <span v-show="!scope.row.iseditor">{{ scope.row.remark }}</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="150"  align="center">
              <template slot-scope="scope">
                <el-button
                  type="warning"
                  size="mini"
                  @click="tableEdit(scope.row, scope)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  @click="tableSave(scope.row)"
                  >保存</el-button
                > </template
              >>
            </el-table-column>
          </el-table>
        </div>

        <el-form-item id="footBtn">
          <el-button
            type="primary"
            plain
            @click="batchAddReport()"
            class="sureBtn"
            >保 存</el-button
          >
          <el-button @click="returnList">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <sameReportCheck
      ref="sameReportCheck"
      :dataList="sameReportList"
      @addReportSure="addReportSure"
    ></sameReportCheck>
  </div>
</template>

<script>
import SameReportCheck from "@/components/SameReportCheck";
import AuthApi from "@/api/system/auth";
import HospitalApi from "@/api/institution/hospital";
import InstitutionApi from "@/api/institution/institution";
import InstitutionItemApi from "@/api/institution/institutionItem";
import HospitalItemApi from "@/api/institution/hospitalItem";
import OfficeApi from "@/api/institution/office";
import DoctorApi from "@/api/institution/doctor";
import ReportApi from "@/api/hsReport/hsReport";
import exportExcel from "@/excel/exportExcel";
import importExcel from "@/excel/importExcel";
export default {
  name: "BatchAddReport",
  data() {
    return {
      pickCurReportStateList: [
        { label: "已收取", value: 5 },
        { label: "已送达", value: 10 }
      ],
      batchAdd: {
        // 批量新增
        open: false, // 默认隐藏
        title: ""
      },
      //导入地址
      importUrl: "",
      fileTemp: null,
      excelData: [],
      tHeader: [
        "平台条码号",
        "医检条码号",
        "患者身份证",
        "患者姓名",
        "患者手机号",
        "患者性别",
        "患者年龄",
        "送检时间",
        "备注"
      ],
      tVariable: [
        "myReportCode",
        "insReportCode",
        "patientCard",
        "patientName",
        "patientPhone",
        "sex",
        "patientAge",
        "reportBeginTime",
        "remark"
      ],
      dataList: [],
      column: [],

      roleRules: {
        // 校验
        hospitalId: [
          {
            required: true,
            message: "请选择医院名称",
            trigger: "blur"
          }
        ]
      },
      userRole: "",
      isMore: false, // 默认为一号一人
      insCodeHide: true,
      loadingIns: false,
      listSex: [
        { value: 1, label: "男" },
        { value: 2, label: "女" },
        { value: "", label: "未选择" }
      ],
      batchForm: {
        // 批量新增 - 表单内容
        hospitalId: "",
        officeId: "",
        doctorId: "",
        hospitalItemIdList:[],//医院组合项目id列表
        institutionId: "",
        insOfficeId: "",
        insReportCode: "",
        reportState: "",
        syUserId: "",
        syUserIdTwo: "", //二级收样员
        syUserIdList: [], // 三级及其后续收样员
        // reportBeginTime: "",
        reportImageList: [],
        isRemind: "0",
        myReportCode: "",
        searchCode: "",
        itemName: "新型冠状病毒核酸检测",
        patientInformation: [], // 患者信息
        insItemIdList: "" // 项目组
      },
      itemNameList: [], // 项目组列表
      itemShow: true, // 项目组的影藏以及显示
      pickerBeginDateBefore: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      },
      batchFormDisabled: false,
      timeDefaultShow: "",
      // 全部的科室 医生 机构 列表
      pickOfficeList: [],
      pickDoctorList: [],
      pickInsOfficeList: [],
      pickInstitutionList: [],
      pickSampleTypeList: [], // 不同机构 对应的 样本项目列表
      pickSyUserList: [],
      hospitalList: [],
      pickHospitalItemList:[], //医院项目组列表
      sameReportList: [] // 相同平台/医检条码号的旧报告单列表
    };
  },
  components: {
    SameReportCheck
  },
  created() {
    this.init();
  },
  methods: {
    //表格编辑
    tableEdit(row, index) {
      row.iseditor = true;
    },
    //表格单行保存
    tableSave(row, index) {
      let phone = row.patientPhone;
      var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/;
      //console.log(phone);
      if (!phonereg.test(phone)) {
        this.$message({
          type: "error",
          message: "手机号码格式有误！"
        });
        return false;
      } else {
        row.iseditor = false;
        return Number(phone);
      }
    },
    // 导入表格
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ===
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type === "application/vnd.ms-excel"
        ) {
          // 开始导入
          importExcel(file, 0, this.tVariable)
            .then(res => {
              //导入的表格转换时往每一列添加一个编辑标识属性
              let resList = res;
              let index = 1;
              for (let i = 0; i < resList.length; i++) {
                resList[i].iseditor = false;
                resList[i].index = index++;
              }
              this.dataList = resList;
            })
            .catch(err => {
              this.$message.error(err);
            });
        } else {
          this.$message({
            type: "error",
            message: "附件格式错误，请删除后重新上传！"
          });
        }
      } else {
        this.$message({ type: "warning", message: "请上传附件！" });
      }
    },

    // 导出表格
    outExe() {
      console.log(JSON.stringify(this.dataList));
      this.$confirm("此操作将导出excel文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.excelData = this.dataList; // 你要导出的数据list
          exportExcel(this.tHeader, this.tVariable, this.excelData, "导出模板");
        })
        .catch(() => {});
    },

    init() {
      this.listSyUser();
      this.listHospital();
    },
    handleCreate() {
      // 父组件调用子组件
      this.batchAdd.open = true; // 显示弹出框
      this.batchAdd.title = "批 量 导 入";
      this.$Utils.clearData(this.batchForm);
      this.batchForm.patientInformation = [];
      this.batchForm.syUserIdList = [];
      this.batchForm.reportImageList = [];
      this.timeDefaultShow = new Date();
      this.typeChange();
    },
    typeChange() {
      // 整体类型发生改变
      this.batchForm.patientInformation = [];
      var type = this.isMore;
      //console.log(type);
      if (type == true) {
        // 一号多人
        var cond = {
          patientName: "",
          patientSex: "",
          patientCard: "",
          patientAge: "",
          patientPhone: "",
          reportBeginTime:"",
          remark: ""
        };
        this.batchForm.patientInformation.push(cond);
      } else if (type == false) {
        // 一号一人
        var otherCond = {
          patientName: "",
          patientSex: "",
          patientCard: "",
          patientAge: "",
          patientPhone: "",
          insReportCode: "",
          myReportCode: "",
          reportBeginTime:"",
          remark: ""
        };
        this.batchForm.patientInformation.push(otherCond);
      }
    },
    // 非空时 校验身份证以及电话 错误就提示 但是不影响保存
    cardChange(val) {
      if (!this.$Utils.isEmptyObject(val)) {
        if (!this.$Utils.isCardNo(val)) {
          this.$Utils.messageError("身份证格式错误");
        }
      }
    },
    phoneChange(val) {
      if (!this.$Utils.isEmptyObject(val)) {
        if (!this.$Utils.isMobile(val)) {
          this.$Utils.messageError("电话号码格式错误");
        }
      }
    },
    getUserRole(val) {
      this.userRole = val;
    },
    clearTable() {
      this.dataList = [];
    },
    listHospital() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        hospitalType: 1
      };
      HospitalApi.getHospitalNameList(cond).then(res => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.hospitalList = res.data.map(item => {
            return {
              value: item.hospitalId,
              label: item.hospitalName
            };
          });
        }, 200);
      });
    },
    hospitalChange() {
      // 医院发生更变 - 加载科室
      let _this = this;
      // 清空其他选项数据
      _this.pickOfficeList = [];
      _this.batchForm.officeId = "";
      _this.pickDoctorList = [];
      _this.batchForm.doctorId = "";
      _this.pickInstitutionList = [];
      _this.pickHospitalItemList = [];
      _this.batchForm.hospitalItemIdList = [];
      _this.batchForm.institutionId = "";
      _this.batchForm.syUserId = "";
      _this.itemNameList = [];
      _this.batchForm.insItemIdList = [];
      _this.itemShow = true;
      if (
        _this.batchForm.hospitalId == "" ||
        _this.batchForm.hospitalId == null
      ) {
        this.$message.error("请先选择医院");
        return;
      }
      

      let cond = {
        hospitalId: this.batchForm.hospitalId
      };
      OfficeApi.getOfficeNames(cond).then(res => {
        setTimeout(() => {
          _this.pickOfficeList = res.data.map(item => {
            return {
              value: item.officeId,
              label: item.officeName
            };
          });
        }, 200);
      });
       // 获取医院组合项目列表
    HospitalItemApi.listHospitalItemsName(cond).then(res=>{
        setTimeout(() => {
          _this.pickHospitalItemList = res.data.map(item => {
            return {
              value: item.itemId,
              label: item.itemName
            };
          });
        }, 200);
      })
    },
     // 医院项目改变
    hospitalItemChange(){
        this.pickInstitutionList = [];
        this.batchForm.institutionId = "";
    },
    officeChange() {
      // 科室信息发生更变 - 加载科室
      let _this = this;
      if (
        _this.batchForm.hospitalId == "" ||
        _this.batchForm.hospitalId == null
      ) {
        this.$message.error("请先选择医院");
        return;
      }
      if (_this.batchForm.officeId == "" || _this.batchForm.officeId == null) {
        this.$message.error("请先选择科室");
        return;
      }
      _this.pickDoctorList = [];
      _this.batchForm.doctorId = "";
      let cond = {
        hospitalId: _this.batchForm.hospitalId,
        officeId: _this.batchForm.officeId
      };
      DoctorApi.getDoctorNames(cond).then(res => {
        setTimeout(() => {
          _this.pickDoctorList = res.data.map(item => {
            return {
              value: item.doctorId,
              label: item.doctorName
            };
          });
        }, 200);
      });
    },
    listInstitutions() {
      // 当input获得焦点时触发
      // 根据医院id 获取匹配的机构
       let _this = this;
      if (!_this.batchForm.hospitalId) {
        this.pickInstitutionList = [];
        this.$message.error("请选择对应医院");
        return;
      }
      _this.loadingIns = true;
      

      if (_this.batchForm.hospitalItemIdList.length>0) {
        let cond = {
         hosItemIds: _this.batchForm.hospitalItemIdList+''
        };
        InstitutionApi.listInsByHosItemId(cond)
          .then(res => {
            setTimeout(() => {
              _this.loadingIns = false;
              _this.pickInstitutionList  = res.data.map(item => {
                return {
                  value: item.institutionId,
                  label: item.institutionName
                };
              });
            }, 200);
          })
          .catch(error => {
            _this.pickInstitutionList = [];
            console.error(error);
          });
      }else{
        let cond = {
          hospitalId: _this.batchForm.hospitalId
        };
        InstitutionApi.getInsByHos(cond)
          .then(res => {
            setTimeout(() => {
              _this.loadingIns = false;
              _this.pickInstitutionList = res.data.map(item => {
                return {
                  value: item.institutionId,
                  label: item.institutionName
                };
              });
            }, 200);
          })
          .catch(error => {
            _this.pickInstitutionList = [];
            console.error(error);
          });
        }
    },
    institutionChange() {
      // 选中、改变 机构选项
      let _this = this;
      _this.pickInsOfficeList = [];
      _this.batchForm.insOfficeId = "";
      let cond = {
        institutionId: _this.batchForm.institutionId
      };
      // 获取机构列表
      OfficeApi.getOfficeNames(cond).then(res => {
        setTimeout(() => {
          _this.pickInsOfficeList = res.data.map(item => {
            return {
              value: item.officeId,
              label: item.officeName
            };
          });
        }, 200);
      });

      // 医检id为97/100 代表重庆医检机构
      if(this.batchForm.institutionId == 97 || _this.batchForm.institutionId == 100 || _this.batchForm.institutionId ==112|| _this.batchForm.institutionId == 124){
          InstitutionItemApi.getInstitutionItemList(cond)
          .then(res => {
            setTimeout(() =>{
              this.itemNameList = res.data.map(item => {
                return {
                  value: item.id,
                  label: item.name
                }
              })
            },200)
          })
          .catch(error => {
            _this.itemNameList = []
            console.error(error)
          })
           this.itemShow = false
           _this.batchForm.insItemIdList = []
          // 当医院项目大于0的时候，这个时候选择了目重庆机构那么就重新开始选择
           if(_this.batchForm.hospitalItemIdList.length>0){
               _this.batchForm.hospitalId = "";

               _this.batchForm.hospitalItemIdList = []
               _this.pickHospitalItemList = []

               
            }
        }else{
          _this.itemNameList = []
          this.itemShow = true
        }

      // 更具机构id 获取样本的code和名称
        InstitutionApi.insSampleTypes(cond)
            .then(res => {
                setTimeout(() => {
                _this.pickSampleTypeList = res.data.map(item => {
                    return {
                    value: item.insSampleCode,
                    label: item.insSampleName
                    }
                })
                }, 200)
            })
            .catch(error => {
                _this.pickSampleTypeList = []
                console.error(error)
            })
    },
    /**
     * 选定特定医检时 出现该项目列表
     */
    itemListChange(value) {
      let _this = this;
      if (value != undefined || value.length >= 0) {
      //   var newList = [];
      //   val.forEach(item => {
      //     let choseValue = item;
      //     let choseList = this.itemNameList.find(item => {
      //       return item.value == choseValue;
      //     });
      //     newList.push(choseList.label);
      //   });
      //   this.batchForm.itemName = newList.join("，");
      //   console.log(this.batchForm.itemName);
      //   console.log(this.batchForm.insItemIdList);
        // 珠海可允许一个条码号绑定不同类型的项目，一个条码号可以扫多次
        if (_this.batchForm.institutionId == 112) {
          return;
        }

        // 筛选出相同科室的项目
        if (value.length == 0 || value.length == 1) {
          let cond = {
            institutionId: _this.batchForm.institutionId
          };
          if (value.length == 1) {
            cond.itemId = value[0];
          }
          InstitutionItemApi.listInsItemNameAndGroup(cond)
            .then(res => {
              setTimeout(() => {
                _this.itemNameList = res.data.map(item => {
                  return {
                    value: item.itemId,
                    label: item.itemName + "-" + item.itemGroup
                  };
                });
              }, 200);
            })
            .catch(error => {
              _this.itemNameList = [];
              console.error(error);
            });
        }
        _this.batchForm.hospitalItemIdList = []
      }
    },
    listSyUser() {
      // 获取收样员列表
      let _this = this;
      AuthApi.listAdminByRole({
        roleId: 4
      }).then(res => {
        setTimeout(() => {
          _this.pickSyUserList = res.data.map(item => {
            return {
              value: item.userId,
              label: item.userName
            };
          });
        }, 200);
      });
    },
    checkInsCodeIsExist() {
      // 校验医检条码号是否重复
      let _this = this;
      if (
        _this.batchForm.insReportCode !== "" &&
        _this.batchForm.insReportCode !== null
      ) {
        _this.insCodeHide = true;
        if (!_this.batchForm.institutionId) {
          this.$message.error("请选择医检机构");
          return;
        }
        let cond = {
          institutionId: _this.batchForm.institutionId,
          insReportCode: _this.batchForm.insReportCode
        };
        ReportApi.getReportCount(cond)
          .then(res => {
            if (res.data && res.data > 0) {
              _this.insCodeHide = false;
            }
          })
          .catch(error => {
            _this.insCodeHide = true;
            console.error(error);
          });
      }
    },
    DeleteTables(index) {
      // 删除最后一列
      var num = this.batchForm.patientInformation.length;
      if (num != 1) {
        // 删除指定列
        this.batchForm.patientInformation.splice(index, 1);
      } else {
        this.$message.error("至少保留一条用户信息！");
      }
    },
    // 次级收样员
    addSubclass() {
      if (!this.batchForm.syUserId) {
        this.$message.error("请选择一级收样员");
        return;
      }
      if (!this.batchForm.syUserIdTwo) {
        this.$message.error("请选择二级收样员");
        return;
      }
      let data = { userId: null };
      this.batchForm.syUserIdList.push(data);
    },
    // 删除次级收样员
    deleteSubclass(index) {
      this.batchForm.syUserIdList.splice(index, 1);
      //console.log(JSON.stringify(this.reportForm.syUserIdList),1111111111)
    },
    // 显示多级收样员label
    changSyUserLabel(index) {
      let result = this.$Utils.numberToChinese(index);
      return result + "级收样员";
    },
    sureReportClicks() {
      console.log(this.batchForm);
      console.log(this.batchForm.patientInformation);
      var userMsgList = this.batchForm.patientInformation;
      if (userMsgList.length == 1) {
        // this.addBeforeCheck();
        console.log(userMsgList[0]);
        // 只有一个用户 就遍历二维数组 校验 名字、身份证、电话 是否重复以及其合法性
      }
    },
    // 提交前校验
    beforeSureCheck() {
      let _this = this;
      //debugger
      let userList = _this.batchForm.patientInformation;
      // 判断是一号多人 or 一号一人
      if (_this.isMore) {
        try {
          userList.forEach(a => {
            if (_this.$Utils.isNullStrict(a.patientName)) {
              throw new Error("提交失败：姓名不能为空！");
            }
          });
        } catch (e) {
          _this.$message.error(e.message);
          return false;
        }

        let code01 = _this.batchForm.insReportCode; //医检条码
        let code02 = _this.batchForm.myReportCode; //康来条码
        if (
          _this.$Utils.isNullStrict(code01) &&
          _this.$Utils.isNullStrict(code02)
        ) {
          _this.$message.error("提交失败：康来、医检条码号不能同时为空！");
          return false;
        }
      } else {
        // 这里是一号一人
        try {
          userList.forEach(a => {
            if (_this.$Utils.isNullStrict(a.patientName)) {
              throw new Error("提交失败：姓名不能为空！");
            }
            if (
              _this.$Utils.isNullStrict(a.myReportCode) &&
              _this.$Utils.isNullStrict(a.insReportCode)
            ) {
              throw new Error("提交失败：康来、医检条码号不能同时为空！");
            }
          });
        } catch (e) {
          _this.$message.error(e.message);
          return false;
        }
      }

      let names = [];
      let idCards = [];
      let myReportCodes = [];
      let insReportCodes = [];
      userList.forEach(a => {
        names.push(a.patientName);
        if (!_this.$Utils.isNullStrict(a.patientCard)) {
          idCards.push(a.patientCard);
        }
        if (!_this.$Utils.isNullStrict(a.myReportCode)) {
          myReportCodes.push(a.myReportCode);
        }
        if (!_this.$Utils.isNullStrict(a.insReportCode)) {
          insReportCodes.push(a.insReportCode);
        }
      });

      let names2 = _this.$Utils.unique(names);
      if (names.length != names2.length) {
        _this.$message.error("提交失败：用户信息中存在相同【姓名】！");
        return false;
      }
      let idCards2 = _this.$Utils.unique(idCards);
      if (idCards.length != idCards2.length) {
        _this.$message.error("提交失败：用户信息中存在相同【身份证】！");
        return false;
      }

      if (!_this.isMore) {
        // 一号一人：分别判断是否同名、同身份证、同编号、同医检条码号
        let myReportCodes2 = _this.$Utils.unique(myReportCodes);
        if (myReportCodes.length != myReportCodes2.length) {
          _this.$message.error("提交失败：用户信息中存在相同【编号】！");
          return false;
        }
        let insReportCodes2 = _this.$Utils.unique(insReportCodes);
        if (insReportCodes.length != insReportCodes2.length) {
          _this.$message.error("提交失败：用户信息中存在相同【医检条码号】！");
          return false;
        }
      }

      return true;
    },
    sureReportClick() {
      let _this = this;
      console.table("导入的表格数据", _this.dataList);
      // 先前端校验
      var cond = {
        isMore: _this.isMore,
        institutionId: _this.batchForm.institutionId,
        insReportCode: _this.batchForm.insReportCode,
        myReportCode: _this.batchForm.myReportCode,
        hospitalId: _this.batchForm.hospitalId,
        reportBatchUserInfoPoList: _this.batchForm.patientInformation
      };
      ReportApi.batchAddCheck(cond).then(res => {
        if (res.status == 0) {
          if (res.data && res.data.length > 0) {
            _this.sameReportList = res.data;
            _this.$refs.sameReportCheck.handleCreate();
          } else {
            _this.batchAddReport();
          }
        } else {
          _this.$Utils.notifyError(res.msg);
        }
      });
    },
    addReportSure() {
      // 客服点击确定为一号多人，隐藏弹出层，提交数据
      this.$refs.sameReportCheck.handleCancel();
      this.batchAddReport();
    },
    batchAddReport() {
      // 保存新增
      let _this = this;
      var cond = {
        isMore: _this.isMore,
        institutionId: _this.batchForm.institutionId,
        hospitalId: _this.batchForm.hospitalId,
        officeId: _this.batchForm.officeId,
        doctorId: _this.batchForm.doctorId,
        hosItemIds:_this.batchForm.hospitalItemIdList,
        syUserId: _this.batchForm.syUserId,
        syUserIdTwo: _this.batchForm.syUserIdTwo,
        syUserIdList: _this.batchForm.syUserIdList,
        myReportCode: _this.batchForm.myReportCode,
        insReportCode: _this.batchForm.insReportCode,
        reportState: Number(_this.batchForm.reportState),
        // reportBeginTime: _this.batchForm.reportBeginTime,
        isRemind: Number(_this.batchForm.isRemind),
        itemName: "新型冠状病毒核酸检测",
        insItemIdList: _this.batchForm.insItemIdList,
        reportBatchUserInfoPoList: _this.dataList
      };
      ReportApi.excelImportAddReport(cond).then(data => {
        this.$Utils.notifySuccess();
        this.$parent.init(); // 调用父组件 刷新页面
        this.returnList();
      });
    },
    /**
     * 下载导入模板
     */
    handleDownloadImportTemplate() {
      const url =
        "https://www.kanglailab.com/download/%E6%A0%B8%E9%85%B8%E6%8A%A5%E5%91%8A%E5%8D%95%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx";
      window.open(url, "location=no");
    },
    returnList() {
      // 取消
      this.batchAdd.open = false;
    }
  }
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
<style scoper>
form .el-row {
  padding: 0 25px;
}
form .tit {
  padding-left: 20px;
}
#groupSyUser .el-form-item__content {
  width: 220px;
}
#footBtn {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
}
.sureBtn {
  margin-right: 131px;
  margin-top: 34px;
}
.tableInput {
  padding: 4px;
  border: 1px solid #d5d5d5;
  border-radius: 5px;
}
</style>
